<template>
  <div>
    <div class="node" v-has="{action: 'iot:pile:list', effect: 'move'}">
    <div :class="[$style.search_box, $style.topSelect]">
      <SearchInput
        placeholder="充电桩名称"
        label="充电桩名称"
        style="margin-right:20px"
        :value="searchs.name"
        :onChange="(val) => changeSearch('name',val)"
        :onBlur="getPile"
      />
      <SearchInput
        placeholder="请输入"
        label="充电桩编号"
        style="margin-right:20px"
        :value="searchs.sn"
        :onChange="(val) => changeSearch('sn',val)"
        :onBlur="getPile"
      />
      <div :class="$style.selectBox">
        <label>状态：</label>
        <el-select
          v-model="searchs.state"
          clearable
          @change="getPile"
          placeholder="请选择"
        >
          <el-option label="正常" :value="1"></el-option>
          <el-option label="离网" :value="2"></el-option>
          <el-option label="停用" :value="0"></el-option>
        </el-select>
      </div>
      <div :class="$style.selectBox">
        <label>选择设备类型：</label>
        <el-select
          v-model="searchs.deviceId"
          clearable
          @change="getPile"
          placeholder="请选择"
        >
          <el-option v-for="item in deviceList" :key="item.id" :value="item.id" :label="item.name" ></el-option>
        </el-select>
      </div>
      <div :class="$style.selectBox">
        <label>站点：</label>
        <el-select
          v-model="searchs.site"
          clearable
          @change="getPile"
          placeholder="请选择"
        >
          <el-option  v-for="item of siteList"
            :key="item.id"
            :value="item.id"
            :label="item.name"></el-option>
        </el-select>
      </div>
      <!-- <SearchSelect
        placeholder="选择站点"
        label="选择站点"
        style="margin-right:20px;"
        :value="searchs.site"
        :loading="loading"
        :options="selectValue"
        :onChange="(val) => searchSelect('site',val)"
        :onSearch="onSearch"
      /> -->
      <div :class="$style.searchBox1" style="margin-left: 20px">
        <el-button size="small" plain  icon="el-icon-search" @click="getPile">查询</el-button>        
      </div>
    </div>
    <Panel title="充电桩管理">
      <div slot='ext' :class="$style.examine">
        <el-button size="mini" v-has="{action: 'iot:pile:add', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>editStore()">新增</el-button>
        <el-button size="mini" v-has="{action: 'iot:ext:update', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>updateExtend()">批量编辑扩展信息</el-button>
        <el-button size="mini" v-has="{action: 'iot:ext:view', effect: 'move'}" class="button-offt"   @click="()=>extendList()">扩展信息列表</el-button>
    </div>
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
    >
    <template slot="colOperation" slot-scope="operation">
        <el-popover trigger="click"  @hide="cancelPwd" placement="top">
         <div :class="$style.tip">
           <p>名称: {{ operation.row.name }}</p>
          <p>密码: {{ pwd }}</p>
         </div>
          <div slot="reference" class="name-wrapper">
            <div  @click="()=>viewPwd(operation.row.id, operation.row.name)" :class="$style.tag" size="medium">{{ operation.row.name }} <i class="el-icon-view"></i></div>
            
            
          </div>
        </el-popover>
        
      </template>
    <template slot="operation" slot-scope="operation">
          <el-button size="mini" icon="el-icon-edit"
            v-has="{action: 'iot:pile:update', effect: 'move'}"
            
            @click="()=>editStore(operation.row)"
          >编辑</el-button>
          <el-button size="mini" icon="el-icon-edit"
          v-has="{action: 'iot:ext:update', effect: 'move'}"
           @click="()=>updateExtend(operation.row.id, operation.row.name)">扩展信息</el-button>
           
          <el-button size="mini" icon="el-icon-refresh"
            v-has="{action: 'iot:pile:pwd:refresh', effect: 'move'}"
            @click="()=>reshPwd(operation.row.sn)"
          >刷新密码</el-button>
          <!-- <el-button size="mini"
            v-has="{action: 'iot:pile:pwd', effect: 'move'}"
            @click="()=>viewPwd(operation.row.id, operation.row.name)"
          >查看密码</el-button> -->
          <el-button size="mini" type="danger" icon="el-icon-delete"
            v-has="{action: 'iot:pile:delete', effect: 'move'}"
            @click="()=>remove(operation.row.id)"
          >删除</el-button>
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    <!-- 添加编辑 start-->
    <ModalPanel 
      :visible='visible'
      title="添加/编辑"
      :onCancel="onCancel"
      :class="$style.bannerDialog"
      :onOk="onSubmit">
      <div>
        <ModifyForm
          :hiddenBtn='true'
          :editColumn='editColumn'
          :updateData="updateData"
          labelWidth='100px'
          ref="configModal"
          :class="$style.ModifyForm"
          :temporaryData='modalData'>
        </ModifyForm>
      </div>
    </ModalPanel>
    <!-- 添加编辑end -->

     <ModalPanel 
      :visible='visible1'
      :showFooter='false'
      title="查看密码"
      :onCancel="onCancel1"
      :class="$style.bannerDialog"
      :onOk="onSubmit">
      <div>
        <div>桩名称： {{names}}</div>
        <div>密码： {{pwd}}</div>
      </div>
    </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'iot:pile:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import SearchSelect from "@/components/SearchSelect";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
export default {
  name: "iotPile",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    SearchSelect,
    ModifyForm,
    ModalPanel
  },
  data() {
    return {
      names: '',
      pwd: '',
      visible1:false,
      modalData1:{},
      tableData: [],
      siteList: [],
      searchs: {
        component: 'pile',
        site:"",
        sn: '',
        name: '',
        deviceId:'',
        type:'',
        state:'',
      },
      // selectValue: [],
      // loading:false,
      deviceList:[],
      pager: {
        component: 'pile',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      operation: true,
      //添加编辑
      visible:false,
      modalData:{},
      editColumn: [
        {
          name: "名称",
          prop: "name",
          type: "text",
          width:24,
          required: true
        },
        {
          name: "桩状态",
          prop: "state",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择状态"},{'id': 1,'name': "正常"},{'id': 2,'name': "离网"},{'id':0, 'name':"停用"}],
          onChange: () => {},
          width:24,
          required: true
        },
        {
          name: "设备类型",
          prop: "deviceId",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择状态"}],
          onChange: () => {},
          width:24,
          required: true
        },
        {
          name: "所属站点",
          prop: "siteId",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择站点"}],
          onChange: () => {},
          width:24,
          required: true
        },
         {
          name: "充电桩编号",
          prop: "sn",
          type: "text",
          width:24,
          required: true
        },
         {
          name: "功率",
          prop: "power",
          type: "number",
          width:24,
          required: true
        },
        {
          name: "备注",
          prop: "mark",
          type: "text",
          width:24,
          required: false
        },
      ],
      //添加编辑end
    };
  },
  mounted() {
    //  this.searchsFnc()
     this.iotSite()
    this.getPile();
    this.onSearchDevice()
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: [
          {
            label: "充电桩编号",
            type: "text",
            prop: "sn",
            align: "center"
          },
          {
            label: "名称",
            type: "colOperation",
            prop: "name",
            align: "center"
          },
         
          {
            label: "在线状态",
            type: "other",
            prop: "online",
            align: "center",
            fnc: val => val == 0 ? '离线': val ==1 ? '在线': '异常',
            class: val => val == 0 ? 'cancel': val ==1 ? 'agree': 'wait'
          },
          {
            label: "桩状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val =>  val ==1 ? '正常' :  val ==2 ? '离网': '停用',
            class: val => val == 0 ? 'cancel': val ==1 ? 'agree': 'out-off'
          },
           {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          {
            label: "密码",
            type: "text",
            prop: "pwd",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:330
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    cancelPwd(){
      this.pwd = ''
    },
    // searchsFnc (){
    //   let searchs = this.$store.getters.searchs
    //   if(searchs &&searchs.component == 'pile'){
    //     this.searchs = searchs
    //   }
    //   let pager = this.$store.getters.pager
    //   if(pager &&pager.component == 'pile'){
    //     this.pager = pager
    //   }
    // },
    //获取站点
    async iotSite(){
      let { list } = await request({
      url: "/iot/site/select",
      method: "POST",
      data: {}
      });
      this.siteList = list
      this.editColumn[3].optionList = list
    },
    async getPile() {
       let state =  this.searchs.state
      let type = this.searchs.type
      let name = this.searchs.name
      let sn = this.searchs.sn
      let siteId = this.searchs.site
      let deviceId = this.searchs.deviceId
      let page = this.pager.current
      let search = objectFilter({name, type, state, sn, page, siteId, deviceId})
      const res = await request({
        url: "/iot/pile/list",
        method: "POST",
        data:  search
      });
      let data =res.page.list
       data.map(item => {
        item.pwd = ''
        return item
       })
       console.log('data',data)
      this.tableData = data
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getPile();
    },
    searchSelect(key, val){
      this.searchs[key] = val;
      this.pager.current = 1;
      this.getPile()
    },
    async onSearchDevice(){
      let { list } = await request({
              url: "/iot/device/select",
              method: "GET",
              data:  {
              }
            });
            this.deviceList = list
            this.editColumn[2].optionList = list
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    // editStore(id){
    //   this.$store.commit('saveSearchs', this.searchs)
    //   this.$store.commit('savePager', this.pager)
    //   this.$router.push({ path: "/iot/pile/info",query:{id:id} })
    // },
    updateExtend(id, name){
      this.$router.push({ path: "/iot/pile/extend", query:{id,name}})
    },
    extendList(id, name){
      this.$router.push({ path: "/iot/pile/extend/list", query:{id,name}})
    },
    //添加编辑start
    editStore(rowData){
      if(rowData){
        this.modalData = {...rowData}
      }else{
        this.modalData ={}
      }
      this.visible = true
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    onCancel(){
      this.visible = false
    },
    async updateData(values){
      const {name, state, id, deviceId, siteId, mark, sn, power} = values
     let url = id ? "/iot/pile/update/id" : "/iot/pile/add"
     let msg = id ? "编辑成功" : "添加成功"
     let res = await request({
       url: url,
       method: 'POST',
       data: {name, state, id, deviceId, siteId, mark, sn, power}
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.visible = false
      this.getPile();
    },
    //添加编辑end

    //
    onCancel1(){
      this.visible1 = false
    },
    async viewPwd(id ,name){
      let res = await request({
        url: `/iot/pile/pwd/${id}`,
        method: "POST",
        data:  {}
      });
      if(res.code !==0) return
      // console.log('index', index)
      // this.$nextTick(() => {
      //   this.tableData[index].pwd = res.pwd
      //   // that.$refs.tree.setCheckedNodes(this.options);
      // });
      // this.visible1 = true
      this.names = name
      this.pwd = res.pwd
     
      // this.$message.success('刷新成功')

    },
    async reshPwd(sn){
      let res = await request({
        url: `/iot/pile/pwd/refresh/${sn}`,
        method: "POST",
        // dataType: 'json',
        data:  {}
        });
         if(res.code !==0) return
       this.$message.success('刷新成功')
    },
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let del = await request({
        url: "/iot/pile/delete",
        method: "POST",
        dataType: 'json',
        data:  [id]
      });
      if (del.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getPile()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.selectBox {
  margin: 4px 0;
  :global {
    label {
      font-size: 14px;
      color: #666666;
    }
    .el-input__inner {
      height: 32px;
    }
    .el-input__suffix {
      line-height: 32px;
    }
    .el-date-editor--datetime{
      width: 200px;
    }
  }
}
.tag{
    background-color: #ecf5ff;
    border-color: #d9ecff;
    font-size: 12px;
    color: #409EFF;
    border-radius: 4px;
    max-width: 110px;
    cursor: pointer;
}
.tip{
      background: #e7c3c3;
    border-radius: 4px;
    padding: 18px 7px;
    color: #040404;
}
</style>